package com.msf.common.utils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.msf.common.annotation.LabelAnnotation;
import com.msf.common.annotation.QueryAnnotation;
import com.msf.common.constant.BizConstant;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Field;

public class AnnotationUtil {

    private static boolean isFirstCondition = true;

    public static <T> QueryWrapper<T> processCommonSearchKeywords(QueryWrapper<T> queryWrapper, Class<T> clazz, Object arg) {
        if (queryWrapper == null) queryWrapper = new QueryWrapper<>();
        Field[] fields = clazz.getDeclaredFields();
        queryWrapper.and(wrapper -> {
            for (Field field : fields) {
                if (field.isAnnotationPresent(QueryAnnotation.class)) {
                    QueryAnnotation annotation = field.getAnnotation(QueryAnnotation.class);
                    if (StringUtils.equals(BizConstant.QUERY_ANNOTATION_TYPE_KEYWORDS, annotation.type())) {
                        String key = StringUtils.isEmpty(annotation.value()) ? field.getName() : annotation.value();
                        field.setAccessible(true);
                        if (!isFirstCondition) {
                            wrapper.or();
                        }
                        wrapper.like(key, arg);
                        isFirstCondition = false;
                    }
                }
            }
        });
        return queryWrapper;
    }

    public static <T> QueryWrapper<T> processCommonSearchAnd(QueryWrapper<T> queryWrapper, Class<T> clazz, Object arg) {
        if (queryWrapper == null) queryWrapper = new QueryWrapper<>();
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            if (field.isAnnotationPresent(QueryAnnotation.class)) {
                QueryAnnotation annotation = field.getAnnotation(QueryAnnotation.class);
                if (StringUtils.equals(BizConstant.QUERY_ANNOTATION_TYPE_AND, annotation.type())) {
                    String key = StringUtils.isEmpty(annotation.value()) ? field.getName() : annotation.value();
                    field.setAccessible(true);
                    queryWrapper.eq(key, arg);
                }
            }
        }
        return queryWrapper;
    }

    public static <T> String getShowField(Class<T> clazz, String type) {
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            if (field.isAnnotationPresent(LabelAnnotation.class)) {
                LabelAnnotation annotation = field.getAnnotation(LabelAnnotation.class);
                if (StringUtils.equals(type, annotation.type())) {
                    return field.getName();
                }
            }
        }
        return null;
    }

}
